package com.jy.modules.cims.subsidiary.controller;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.jy.modules.cims.common.CimsConstant;
import com.jy.modules.cims.common.controller.CimsBaseController;
import com.jy.modules.cims.common.controller.ExportController.ExportUtil;
import com.jy.modules.cims.common.exception.CimsExceptionConstant;
import com.jy.modules.cims.common.exception.SysAssistException;
import com.jy.modules.cims.common.sysUtils.DateTimeUtils;
import com.jy.modules.cims.component.sysAssist.ExportAndImport;
import com.jy.modules.cims.data.dto.form.tbj.TbjAuditResulTotalDto;
import com.jy.modules.cims.data.dto.form.tbj.TbjLoanResulTotalDto;
import com.jy.modules.cims.data.dto.form.tbj.TbjRaisePlanTotalDto;
import com.jy.modules.cims.subsidiary.service.SubsidiaryService;
import com.jy.platform.core.message.DataMsg;
import com.jy.platform.core.message.PageParameter;
import com.jy.platform.core.message.PageUtil;
import com.jy.platform.core.message.QueryReqBean;
import com.jy.platform.restservice.exception.AbaboonException;

/**
 * @classname: SubsidiaryController
 * @description: 定义 合约 控制层
 * @author: dell
 */
@Controller
@Scope("prototype")
@RequestMapping("/tbjForm")
public class TbjFormController extends CimsBaseController{
	
    private static final Logger logger = LoggerFactory.getLogger(TbjFormController.class);
	
    @Autowired
    @Qualifier("com.jy.modules.cims.subsidiary.service.SubsidiaryService")
    public SubsidiaryService subsidiaryService;
	
	/**
     * 通过 Controller 请求 跳转 进入至相关 页面
     */
    @RequestMapping(value = "/prepareExecute/{operate}")
    public ModelAndView execute(@PathVariable("operate") String operate, HttpServletRequest request)
            throws AbaboonException {
        ModelAndView model = new ModelAndView();

        if ("toQuery".equals(operate)) {// 跳转至 募集计划与贷款转出包对照关系报表页面
        	model.setViewName("cims/subsidiary/tbj/queryTCMmRaisePlanAndLoan");
        } else if ("toTbjAuditResult".equals(operate)) {// 跳转至 铜板街审核页面
            model.setViewName("cims/subsidiary/tbj/queryTbjAuditResultForm");
        } else if ("toTbjLoanResult".equals(operate)) {// 跳转至 铜板街放款页面
            model.setViewName("cims/subsidiary/tbj/queryTbjLoanResultForm");
        } 

        return model;
    }
    
    /**
     * 铜板街审核结果报表
     * @param request
     * @param response
     * @param dataMsg
     * @return
     */
    @RequestMapping(value = "/TbjAuditResult")
    @ResponseBody
    public DataMsg queryTbjAuditResult(HttpServletRequest request, TbjAuditResulTotalDto dto,@ModelAttribute DataMsg dataMsg) {
    	Map<String, Object> searchParams = new HashMap<String, Object>();
        searchParams.put("dto", dto);
        QueryReqBean params = new QueryReqBean();
        params.setSearchParams(searchParams);
        PageParameter pageInfo = PageUtil.toPageParameter(dataMsg);
        params.setPageParameter(pageInfo);
        
        List<TbjAuditResulTotalDto> list = subsidiaryService.getTbjAuditResult(params.getSearchParams());

        dataMsg.setData(list);
        dataMsg.setTotalRows(pageInfo.getTotalCount());
        return dataMsg;

    }
    
    /**
     * 铜板街放款结果报表
     * @param request
     * @param response
     * @param dataMsg
     * @return
     */
    @RequestMapping(value = "/TbjLoanResult")
    @ResponseBody
    public DataMsg queryTbjLoanResult(HttpServletRequest request, TbjLoanResulTotalDto dto,@ModelAttribute DataMsg dataMsg) {
		
    	Map<String, Object> searchParams = new HashMap<String, Object>();
        searchParams.put("dto", dto);
        QueryReqBean params = new QueryReqBean();
        params.setSearchParams(searchParams);
        PageParameter pageInfo = PageUtil.toPageParameter(dataMsg);
        params.setPageParameter(pageInfo);
        
        List<TbjLoanResulTotalDto> list = subsidiaryService.getTbjLoanResult(params.getSearchParams());

        dataMsg.setData(list);
        dataMsg.setTotalRows(pageInfo.getTotalCount());
        return dataMsg;

    }
    
    /**
     * 导出统计查询铜板街审核结果
     * @param request
     * @param dto
     * @param dataMsg
     * @return
     */
    @RequestMapping(value = "/exportTbjAuditFormTotal")
	@ResponseBody
    public void exportTbjAuditFormTotal(HttpServletRequest request,HttpServletResponse response, TbjAuditResulTotalDto dto, @ModelAttribute DataMsg dataMsg){
    	
    	String searchValue = this.getParameterString("searchValue");
    	Date date = new Date();
    	SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmss");
    	formatter.format(date);
		String dealDate = formatter.format(date);
		String fileName = "铜板街审核结果报表"+dealDate;
    	
    	Map<String, Object> searchParams = new HashMap<String, Object>();
    	dto.setPackageCode(searchValue);
		searchParams.put("dto", dto);
		QueryReqBean params = new QueryReqBean();
		params.setSearchParams(searchParams);
		PageParameter pageInfo = PageUtil.toPageParameter(dataMsg);
		params.setPageParameter(pageInfo);
		
    	List<TbjAuditResulTotalDto> list = subsidiaryService.getTbjAuditResult(params.getSearchParams());
    	ExportAndImport<TbjAuditResulTotalDto> exportAndImport = new ExportAndImport<TbjAuditResulTotalDto>();
    	String columnCode = CimsConstant.TBJ_AUDIT_RESULT_EXPORT_CODE;
    	String columnName = CimsConstant.TBJ_AUDIT_RESULT_EXPORT_NAME;
		HSSFWorkbook workbook;
		try {
			workbook = exportAndImport.exportExcelSubsidiary(fileName, columnCode, columnName, list);
			write(workbook, fileName, response);
		} catch (IOException e) {
			dataMsg.failed(e.getMessage());
			throw new SysAssistException(CimsExceptionConstant.TBJ_FORM_FAILED + ":审核结果" + e);
		}
    }
    
    /**
     * 导出统计查询铜板街放款结果
     * @param request
     * @param dto
     * @param dataMsg
     * @return
     */
    @RequestMapping(value = "/exportTbjLoanFormTotal")
	@ResponseBody
    public void exportTbjLoanFormTotal(HttpServletRequest request,HttpServletResponse response, TbjLoanResulTotalDto dto, @ModelAttribute DataMsg dataMsg){
    	
    	String searchValue = this.getParameterString("searchValue");
    	Date date = new Date();
    	SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmss");
    	formatter.format(date);
		String dealDate = formatter.format(date);
		String fileName = "铜板街放款结果报表"+dealDate;
    	
    	Map<String, Object> searchParams = new HashMap<String, Object>();
    	dto.setPackageCode(searchValue);
		searchParams.put("dto", dto);
		QueryReqBean params = new QueryReqBean();
		params.setSearchParams(searchParams);
		PageParameter pageInfo = PageUtil.toPageParameter(dataMsg);
		params.setPageParameter(pageInfo);
		
    	List<TbjLoanResulTotalDto> list = subsidiaryService.getTbjLoanResult(params.getSearchParams());
    	ExportAndImport<TbjLoanResulTotalDto> exportAndImport = new ExportAndImport<TbjLoanResulTotalDto>();
    	String columnCode = CimsConstant.TBJ_LOAN_RESULT_EXPORT_CODE;
    	String columnName = CimsConstant.TBJ_LOAN_RESULT_EXPORT_NAME;
		HSSFWorkbook workbook;
		try {
			workbook = exportAndImport.exportExcelSubsidiary(fileName, columnCode, columnName, list);
			write(workbook, fileName, response);
		} catch (IOException e) {
			dataMsg.failed(e.getMessage());
			throw new SysAssistException(CimsExceptionConstant.TBJ_FORM_FAILED + ":放款结果" + e);
		}
    }
    
    /**
  	 * 页面输出
  	 * 
  	 * @param workbook
  	 * @param fileName
  	 * @param response
  	 * @throws IOException
  	 */
  	private void write(HSSFWorkbook workbook, String fileName, HttpServletResponse response) throws IOException {

  		try {
  			
  			response.setContentType("application/vnd.ms-excel");
  			response.setContentType("application/vnd.openxmlformatSs-officedocument.spreadsheetml.sheet");
  			response.setCharacterEncoding("UTF-8");
  			response.setHeader("content-disposition", "attachment;filename=" + new String(fileName.getBytes("gb2312"), "ISO8859-1") + ".xls");
  			workbook.write(response.getOutputStream());
  			response.getOutputStream().flush();
  		} catch (Exception e) {
  			throw new SysAssistException(CimsExceptionConstant.EXPORT_EXCEL_FAIL + e.getMessage());
  		} finally {
  			response.getOutputStream().close();
  		}
  	}
    /**
     * 
     * @Description 统计募集计划与贷款转出包对照关系
     * @param request
     * @param dto
     * @param dataMsg
     * @throws Exception   
     * @author zhangmi
     * @date 2015-9-24
     */
    @RequestMapping(value = "/queryTbjRaisePlanAndLoan")
    @ResponseBody
    public DataMsg queryTbjRaisePlanAndLoan(HttpServletRequest request, TbjRaisePlanTotalDto dto, @ModelAttribute DataMsg dataMsg) throws Exception {
        
    	Map<String, Object> searchParams = new HashMap<String, Object>();
    	searchParams.put("dto", dto);
        QueryReqBean params = new QueryReqBean();
        params.setSearchParams(searchParams);
    	PageParameter pageInfo = PageUtil.toPageParameter(dataMsg);
		params.setPageParameter(pageInfo);
        List<TbjRaisePlanTotalDto> list = subsidiaryService.getTbjRaisePlanAndLoanByPaging(params.getSearchParams());
        dataMsg.setData(list);
        dataMsg.setTotalRows(pageInfo.getTotalCount());
        return dataMsg;
    }
    /**
     * 
     * @Description 统计募集计划与贷款转出包对照关系导出
     * @param request
     * @param dto
     * @param response
     * @param dataMsg
     * @author zhangmi
     * @date 2015-9-24
     */
    @RequestMapping(value = "/exportTbjRaisePlanAndLoan")
    public ModelAndView exportTbjRaisePlanAndLoan(HttpServletRequest request, TbjRaisePlanTotalDto dto, HttpServletResponse response,@ModelAttribute DataMsg dataMsg){
    	try {
	    	Map<String, Object> searchParams = new HashMap<String, Object>();
	    	searchParams.put("dto", dto);
	        QueryReqBean params = new QueryReqBean();
	        params.setSearchParams(searchParams);
	    	List<TbjRaisePlanTotalDto> list = subsidiaryService.exportTbjRaisePlanAndLoan(params.getSearchParams());
	        ExportAndImport<TbjRaisePlanTotalDto> eai = new ExportAndImport<TbjRaisePlanTotalDto>();
	        String fileName = "募集计划与贷款转出包对照关系"+DateTimeUtils.getDateTime("yyyyMMddHHmmss");
	        String raisePlanCode = CimsConstant.TBJ_RAISE_PLAN_CODE;
	        String raisePlanName = CimsConstant.TBJ_RAISE_PLAN_NAME;
	        HSSFWorkbook workbook = eai.exportExcelSubsidiary(fileName, raisePlanCode, raisePlanName, list);
	        ExportUtil.write(workbook, fileName, response);
	    	return null;
    	} catch (Exception e) {
    		e.printStackTrace();
            logger.error("执行方法exportTbjRaisePlanAndLoan异常：", e);
            ModelAndView m = new ModelAndView();
            m.setViewName("cims/tbjForm/queryTbjRaisePlanAndLoan");
            m.addObject("error", "导出报表异常！");
            return m;
		}
    }
}
